<template>
  <div class="supervise-list-container">
    <StatisticTabsHeader v-model="currentTabKey"
                         :tabsList="statisticListArr"
                         @handleChange="handleHeaderTabChange"></StatisticTabsHeader>
    <div class="allocation-list-main">
      <div v-show="isShowHeight"
           style="height: 8px"></div>
      <div :id="searchConditionContainerId"></div>
      <div class="allocation-list-header">
        <CommonCounter v-if="selectedRowKeys.length"
                       :total="pagination.total"
                       :currentSelected="selectedRowKeys.length"
                       @cancelSelected="cancelSelected" />
        <div style="flex: 1; overflow: hidden">
          <CommonToolbar :allToolBtns="allToolBtns"
                         @buttonClick="toolbarClick">
          </CommonToolbar>
        </div>
        <div class="search-part">
          <div style="display: inline-block; width: 272px">
            <a-input-search :placeholder="$i18n('collaboration.new.template.search.keyWords')"
                            style="width: 272px"
                            :allowClear="true"
                            @change="onInputSearchValueChange"
                            @search="onSearch" />
          </div>
          <div style="margin-left: 12px; display: flex">
            <SearchCondition :containerParentId="searchConditionContainerId"
                             :conditions="searchConditions"
                             @valueChange="conditionValueChange"
                             @expandChange="expandChange"></SearchCondition>
          </div>
        </div>
      </div>
      <div class="allocation-list-content"
           v-if="statisticListArr.length > 0">
        <AVirtuallyTable ref="avirtuallyTable"
                         :row-selection="{
          columnWidth: 60,
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          // onSelect: onSelectRecord
        }"
                         rowKey="affairId"
                         :pagination="true"
                         :paginationOption="pagination"
                         :columns="columns"
                         :loading="loading"
                         size="small"
                         :openVirtuallyModel="true"
                         :dataSource="dataSource"
                         :titleRightMenus="titleRightMenus"
                         @paginationChange="handleTableChange"
                         @rowClick="rowClick"
                         @paginationShowSizeChange="paginationShowSizeChange">
        </AVirtuallyTable>
      </div>
    </div>
  </div>
</template>

<script>
  const typeEnum = {
    waitAllocation: 1,
    waitGrab: 2,
    waitDeal: 3
  };
  import CommonToolbar from '@/components/common-toolbar/index';
  import CommonCounter from '@/components/common-counter/index';
  import SearchCondition from '@/components/search-condition/index.vue';
  import AVirtuallyTable from '@/ant-virtually-table/table.vue';
  import StatisticTabsHeader from '@/components/statistic-tabs-header/index.vue';
  import { getUrlSearchParams, loadComponentsThemeDefaultCSS } from '@/utils';
  import { formatRequestDataToJSON, loadExtendResource } from '@/utils/api';
  import * as Fiber from 'fiber';
  export default {
    name: 'AllocationList',
    components: {
      CommonToolbar,
      CommonCounter,
      SearchCondition,
      AVirtuallyTable,
      StatisticTabsHeader
    },
    data() {
      return {
        urlParamObj: {},
        statisticListArr: [],
        currentTabKey: 'allocation',
        searchConditionContainerId: 'search-condition-container-parent',
        selectedRowKeys: [],
        pagination: {
          page: 1,
          total: 0
        },
        showCounter: false,
        allToolBtns: [],
        dataSource: [],
        columns: [],
        titleRightMenus: {
          asc: true,
          desc: true,
          freeze: true,
          fieldset: true
        },
        isShowHeight: false,
        hasClick: false,
        isFirstCreate: true,
        searchConditions: [],
        searchValue: '',
        selectedRows: [],
        loading: false
      };
    },
    created() {
      //高级条件
      this.seniorConditions = null;
      this.urlParamObj = getUrlSearchParams();
      this.initTableHeader();
      this.initToolbar();
      this.initTableData();
      loadComponentsThemeDefaultCSS(window._ctxPath + window._ctpSkinUrl);
    },
    methods: {
      initToolbar() {
        this.$set(this, 'allToolBtns', []);
        this.cancelSelected();
        //全部
        if (this.currentTabKey === 'waitDeal') {
          this.allToolBtns.push({
            id: 'urgeDeal',
            name: this.$i18n('allocation.button.text.allocationRepeat')
          });
        } else {
          this.allToolBtns.push({
            id: 'urgeDeal',
            name: this.$i18n('allocation.button.text.allocation')
          });
        }
      },
      initTableData() {
        this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.cleanSelection();
        const temp = {
          allocationType: typeEnum[this.currentTabKey],
          subject: this.searchValue || '',
          sender: this.seniorConditions?.startMemberName || '',
          createDate: this.seniorConditions?.createDate
            ? `${this.seniorConditions?.createDate.startDate}#${this.seniorConditions?.createDate.endDate}`
            : ''
        };
        if (this.currentTabKey === 'waitDeal') {
          temp.allocationDate = temp.allocationDate = this.seniorConditions?.allocationDate
            ? `${this.seniorConditions?.allocationDate.startDate}#${this.seniorConditions?.allocationDate.endDate}`
            : '';
        } else {
          temp.receiveDate = this.seniorConditions?.receiveDate
            ? `${this.seniorConditions?.receiveDate.startDate}#${this.seniorConditions?.receiveDate.endDate}`
            : '';
        }
        const sendParams = [{ page: this.pagination.page, size: this.pagination.pageSize }, temp];
        const args = `managerMethod=findAllocationPageByCondition&arguments=${formatRequestDataToJSON(
          sendParams
        )}`;
        this.loading = true;
        if (this.cancelToken && this.cancelToken.cancel) {
          this.cancelToken.cancel();
          this.cancelToken = null;
        }
        this.cancelToken = axios.CancelToken.source();
        const url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=allocationManager&rnd=81900`;
        window.axios
          .post(url, args, {
            cancelToken: this.cancelToken.token,
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            }
          })
          .then((data) => {
            const result = data.data;
            this.loading = false;
            if (result) {
              this.pagination.total = result.total;
              this.pagination.pageSize = result.size;
              this.dataSource = result.data;
            }
          });
      },
      dataTypeChange(key) {
        this.currentTabKey = key;
        this.initToolbar();
        //每一次切换统计需要请求表格数据，重新渲染
      },
      cancelSelected() {
        this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.cleanSelection();
        this.showCounter = false;
      },
      onInputSearchValueChange(e) {
        this.searchValue = e.target.value;
      },
      onSearch(e) {
        this.searchValue = e;
        this.pagination.page = 1;
        this.initTableData();
        //TODO: 搜索
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys;
      },
      onSelectRecord(record, selected, selectedRows) {
        this.selectedRows = selectedRows;
      },
      handleTableChange(page, pageSize) {
        this.cancelSelected();
        this.pagination.page = page;
        this.pagination.pageSize = pageSize;
        this.initTableData();
      },
      paginationShowSizeChange(current, size) {
        this.pagination.page = 1;
        this.pagination.pageSize = size;
        this.initTableData();
      },
      handleExpand(val) {
        this.isShowHeight = val;
      },
      toolbarClick() {
        if (this.selectedRowKeys.length < 1) {
          Fiber.message.warning(this.$i18n('allocation.alert.info.nochoice'));
          return;
        }
        let id_checkbox = this.selectedRowKeys;
        // for (const iterator of this.selectedRowKeys) {
        //   id_checkbox.push(this.dataSource[iterator]);
        // }
        if (id_checkbox.length <= 0) {
          //请选择要编辑的事项
          $.alert(this.$i18n('allocation.alert.info.nochoice'));
          return true;
        }
        if (id_checkbox.length > 1) {
          //只能选择一项事项进行编辑
          $.alert(this.$i18n('allocation.alert.info.onlyone'));
          return true;
        }
        if (id_checkbox.length === 1) {
          let params = {
            affairId: id_checkbox[0],
            callback: this.freshData
          };
          // 调起分配选人
          this.manualAllocation(params);
        }
      },
      freshData() {
        this.cancelSelected();
        this.initTableHeader();
        this.initTableData();
      },
      manualAllocation(param) {
        if (this.hasClick) {
          return;
        }

        this.hasClick = true;

        let affairId = param['affairId'];
        if (!affairId) {
          this.hasClick = false;
          $.alert('传入参数错误');
          return;
        }

        let pendingAllocatedMessage = window.callBackendMethod(
          'allocationManager',
          'getPendingAllocatedMessage',
          affairId
        );
        let errorMsg = pendingAllocatedMessage['errorMsg'];
        if (errorMsg) {
          $.messageBox({
            title: this.$i18n('common.system.hint.label'), //系统提示
            type: 0,
            imgType: 2,
            msg: errorMsg,
            ok_fn: () => {
              this.hasClick = false;
            },
            cancel_fn: () => {
              this.hasClick = false;
            },
            closeParam: {
              show: true,
              handler: () => {
                this.hasClick = false;
              }
            }
          });
          return;
        }

        let selectPeopleSize = pendingAllocatedMessage['selecPeopleSize'];

        let dialogButtons = [];

        if (pendingAllocatedMessage['member'].length == 0) {
          dialogButtons.push({
            text: this.$i18n('allocation.select.org.js'),
            isEmphasize: true,
            handler: () => {
              let maxSize = selectPeopleSize;

              let selParam = {
                panels: 'Department,BusinessDepartment,Team,Post,Outworker,Level',
                maxSize: maxSize,
                minSize: 1
              };

              //设置按钮类型
              selParam.btnType = 'addMember';

              manualAllocationDialog.getReturnValue(selParam);
            }
          });
        }

        dialogButtons.push({
          text: this.$i18n('common.button.ok.label'), //确定
          handler: () => {
            let memberIds = manualAllocationDialog.getReturnValue({ innerButtonId: 'ok' });
            if (!memberIds) {
              return;
            }
            this.hasClick = false;
            window.callBackendMethod(
              'allocationManager',
              'transAllocatedMember',
              affairId,
              memberIds,
              {
                success: (memberId) => {
                  manualAllocationDialog.close();
                  if (memberId.success == false) {
                    $.alert({
                      msg: memberId.msg,
                      targetWindow: window,
                      ok_fn: () => {}
                    });
                  } else {
                    if (param.callback) {
                      param.callback();
                    }
                  }
                },
                error: (request, settings, e) => {
                  $.alert(e);
                }
              }
            );
          }
        });

        dialogButtons.push({
          text: this.$i18n('common.button.cancel.label'), //取消
          handler: () => {
            this.hasClick = false;
            manualAllocationDialog.close();
          }
        });

        let manualAllocationDialog = $.dialog({
          targetWindow: window.getCtpTop(),
          id: 'manualAllocationDialog',
          url:
            window._ctxPath + '/workflow/allocation.do?method=manualAllocation&affairId=' + affairId,
          width: 660,
          height: 460,
          title: this.$i18n('allocation.select.node.member.js'), //选择节点执行人
          transParams: {
            pendingAllocatedMessage: pendingAllocatedMessage
          },
          closeParam: {
            show: true,
            handler: () => {
              this.hasClick = false;
            }
          },
          buttons: dialogButtons
        });
      },
      initTableHeader() {
        const headerParams = {
          // 页面唯一标识（取值参照PageKey）
          key: 'LIST_ALLOCATION_SECTION',
          // 来源 0菜单 1栏目 （取值参照FromType）
          // from: 1,
          // 终端 0 pc 1 mobile （取值参照PlatformType）
          platform: 0,
          // 业务传参，由业务决定（后续可在元数据拦截器中获取到）
          arguments: {
            userId: window._currentUser.id,
            currentPanel: this.currentTabKey,
            subject: this.searchValue || '',
            sender: this.seniorConditions?.startMemberName || '',
            createDate: this.seniorConditions?.createDate
              ? `${this.seniorConditions?.createDate.startDate}#${this.seniorConditions?.createDate.endDate}`
              : '',
            allocationDate: this.seniorConditions?.allocationDate
              ? `${this.seniorConditions?.allocationDate.startDate}#${this.seniorConditions?.allocationDate.endDate}`
              : ''
          }
        };
        const url = `${window._ctxPath}/rest/global/metadata/list`;
        window.axios.post(url, headerParams).then((data) => {
          if (data.data.code === 0) {
            const { tableColumns, searchConditions, pageHead, extra } = data.data.data;
            loadExtendResource(extra.extendResources);
            this.searchConditions = searchConditions.filter((item) => item.key !== 'subject');
            this.statisticListArr = (pageHead?.items || []).map((item) => {
              return {
                key: item.key.split('Num')[0],
                title: item.title,
                value: item.value
              };
            });
            if (this.isFirstCreate) {
              this.currentTabKey = this.statisticListArr[0].key;
              this.isFirstCreate = false;
            }
            this.getStaticData();
            this.columns = (tableColumns || []).splice(1).map((item) => {
              return {
                title: item.title,
                dataIndex: item.key,
                key: item.key,
                ellipsis: true,
                width: item.width,
                dropdownMenus: {
                  asc: true,
                  desc: true,
                  freeze: true,
                  fieldset: true
                },
                customCell: () => {
                  return {
                    style: {
                      padding: '0 8px',
                      cursor: 'pointer'
                    }
                  };
                }
              };
            });
          }
        });
      },
      //获取统计数据
      getStaticData() {
        const sendParams = [
          {
            allocationType: typeEnum[this.currentTabKey]
          }
        ];
        const args = `managerMethod=getAllocationTotalNum&arguments=${JSON.stringify(sendParams)}`;
        const url = `${window._ctxPath}/ajax.do?method=ajaxAction&managerName=allocationManager&rnd=6714`;
        window.axios
          .post(url, args, {
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            }
          })
          .then((result) => {
            const data = result.data;
            this.statisticListArr.forEach((item) => {
              item.value = data[item.key + 'Num'] || 0;
            });
          });
      },
      handleHeaderTabChange(key) {
        this.pagination.page = 1;
        this.currentTabKey = key;
        this.initTableHeader();
        this.initTableData();
        this.initToolbar();
        this.searchValue = '';
      },
      rowClick(data) {
        let url =
          window._ctxPath +
          '/collaboration/collaboration.do?method=summary&openFrom=' +
          this.currentTabKey +
          '&affairId=' +
          data.affairId +
          (window.CsrfGuard ? window.CsrfGuard.getUrlSurffix() : '');

        if (url.indexOf('edoc') == -1 && url.indexOf('govdoc') == -1) {
          url += '&showTab=true';
        }

        this.showSummayDialogByURL(url);
      },
      showSummayDialogByURL(url) {
        try {
          //公文、协同都是affairId，会议是Id
          var affairIdIndex = url.indexOf('affairId');
          var idIndex = url.indexOf('id');
          var id = '';
          if (affairIdIndex != -1) {
            id = window.getMultyWindowId('affairId', url);
            this.openWindow({ url: url, id: id });
          } else if (idIndex != -1) {
            id = window.getMultyWindowId('id', url);
            this.openWindow({ url: url, id: id });
          } else {
            this.openWindow({ url: url });
          }
        } catch (e) {
          console.error(e);
        }
      },
      openWindow(obj) {
        var url = obj.url;
        var a8Top = window.getA8Top();
        if (a8Top.isMultipleTabs && url.indexOf('showTab=true') != -1 && !this.isOcipSummary(obj)) {
          a8Top.openCtpWindow(obj);
        } else {
          window.openCtpWindow(obj);
        }
      },
      //ocip推送过来的数据，不走多页签
      isOcipSummary(obj) {
        if (window._hasPlugin('ocip')) {
          let url = obj.url;
          if (url.indexOf('method=summary&') != -1 && url.indexOf('showTab=true') != -1) {
            let params = url.split('&');

            for (let i = 0; i < params.length; i++) {
              if (params[i].indexOf('affairId=') == -1) {
                continue;
              }
              let affairIds = params[i].split('=');
              if (affairIds[0] == 'affairId' && affairIds[1]) {
                return window.callBackendMethod(
                  'ocipColManager',
                  'checkIsExchangeAffair',
                  affairIds[1]
                );
              }
            }
          }
        }
        return false;
      },
      expandChange() {
        this.$nextTick(() => {
          this.$refs.avirtuallyTable && this.$refs.avirtuallyTable.resizeTable();
        });
      },
      conditionValueChange(data) {
        this.pagination.page = 1;
        this.seniorConditions = data;
        this.initTableData();
      }
    }
  };
</script>
<style>
  @import url('../../assets/css/common.css');
</style>
<style lang="scss">
  .supervise-list-container {
    background-color: #ffffff;
    text-align: center;
    color: #2c3e50;
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;

    .statistic-container {
      height: 72px;
      background-color: #fff;
      margin: 12px 0 0 12px;
      border-radius: 4px;
      box-sizing: border-box;
      display: flex;
      justify-content: flex-start;

      .statistic-item {
        cursor: pointer;
        min-width: 160px;
        width: 220px;
        color: #666;
        &:hover {
          color: #0077ff;
          color: var(--theme-brand4, #0077ff);
        }

        .common-item {
          margin-top: 9px;
        }

        .menu-item {
          border-right: 2px solid #e4e7ed;

          .item_text {
            padding-left: 31px;
            text-align: left;
            font-family: PingFangSC-Medium;
            font-weight: 500;
            font-size: 14px;
            letter-spacing: 0;
            margin-bottom: 0;
          }

          .statistic-count {
            display: flex;
            padding-left: 31px;
            text-align: left;
            height: 29px;
            line-height: 29px;
            margin-top: 3px;

            .statistic-icon {
              margin-right: 14px;
              width: 28px;
              height: 28px;
              border-radius: 50%;
              background-color: #f6f8fb;
              text-align: center;
              display: inline-block;

              .icon {
                color: #bfbfbf;
              }
            }

            .statistic-value {
              margin-right: 14px;
              font-weight: 700;
              font-size: 22px;
              color: #666;
              letter-spacing: 0;
            }

            .statistic-unit {
              font-weight: 400;
              font-size: 14px;
              color: #666;
              letter-spacing: 0;
            }
          }
        }

        .active-item .item_text {
          color: #0077ff;
          color: var(--theme-brand6, #0077ff);
        }

        .active-item .statistic-count .statistic-icon {
          background-color: #e5f1ff;
        }

        .active-item .statistic-count .statistic-icon .icon {
          color: #0077ff;
        }

        .active-item .statistic-count .statistic-value {
          color: #0077ff;
        }

        .active-item .statistic-count .statistic-unit {
          color: #000;
        }
      }

      .statistic-item-active {
        border-bottom: 2px solid #0077ff;
        border-radius: 2px;
      }
    }

    .allocation-list-main {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      top: 44px;
      display: flex;
      flex-direction: column;
      padding-left: 16px;
      .allocation-list-header {
        display: flex;
        padding: 12px 16px 12px 0;
        height: 54px;
        box-sizing: border-box;
        justify-content: flex-start;

        .statistic-item {
          cursor: pointer;
          min-width: 160px;
          width: 220px;
          color: #666;
          &:hover {
            color: #0077ff;
            color: var(--theme-brand4, #0077ff);
          }

          .common-item {
            margin-top: 9px;
          }

          .menu-item {
            border-right: 2px solid #e4e7ed;

            .item_text {
              padding-left: 31px;
              text-align: left;
              font-family: PingFangSC-Medium;
              font-weight: 500;
              font-size: 14px;
              letter-spacing: 0;
              margin-bottom: 0;
            }

            .statistic-count {
              display: flex;
              padding-left: 31px;
              text-align: left;
              height: 29px;
              line-height: 29px;
              margin-top: 3px;

              .statistic-icon {
                margin-right: 14px;
                width: 28px;
                height: 28px;
                border-radius: 50%;
                background-color: #f6f8fb;
                text-align: center;
                display: inline-block;

                .icon {
                  color: #bfbfbf;
                }
              }

              .statistic-value {
                margin-right: 14px;
                font-weight: 700;
                font-size: 22px;
                color: #666;
                letter-spacing: 0;
              }

              .statistic-unit {
                font-weight: 400;
                font-size: 14px;
                color: #666;
                letter-spacing: 0;
              }
            }
          }

          .active-item .item_text {
            color: #0077ff;
            color: var(--theme-brand6, #0077ff);
          }

          .active-item .statistic-count .statistic-icon {
            background-color: #e5f1ff;
          }

          .active-item .statistic-count .statistic-icon .icon {
            color: #0077ff;
          }

          .active-item .statistic-count .statistic-value {
            color: #0077ff;
          }

          .active-item .statistic-count .statistic-unit {
            color: #000;
          }
        }

        .statistic-item-active {
          border-bottom: 2px solid #0077ff;
          border-radius: 2px;
        }
      }

      .allocation-list-content {
        position: relative;
        flex: 1;
        padding: 0;
        overflow: hidden;
        > div {
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
        }
      }

      .search-part {
        display: flex;
        justify-content: flex-end;
        overflow: hidden;
        margin-left: 100px;
      }

      .allocation-list-content {
        flex: 1;
        padding: 0 10px 0 20px;
      }

      .tag-show {
        border-radius: 2px;
        border: none;
      }
    }
  }
</style>
